﻿/// <reference path="../../../_references.js" />

HostPipe.UI.DomainsManager = function () {
    this.element = $('#DomainContent');
    this.domainID = 0;
    this.isDomain = false;
    this.isDomainLinks = false;
    this.isSettings = true;
}

HostPipe.UI.DomainsManager.prototype = {
    _applyViewModel: function (element) {
        if (element)
            ko.applyBindings(this.viewModel, element.get(0));
        else
            ko.applyBindings(this.viewModel, this.element.get(0));
    },
    _createViewModel: function () {
        this.viewModel = {
            isNewDomain: ko.observable(true),
            sectionHeader: ko.observable('Add Domain'),

            onEdit: $.proxy(this._onEdit, this),
            onEditSettings: $.proxy(this._onEditSettings, this),
            onDelete: $.proxy(this._onDelete, this),
            onDeleteDomainLinks: $.proxy(this._onDeleteDomainLinks, this),
            onManage: $.proxy(this._onManage, this),
            onNewDomain: $.proxy(this._onNewDomain, this),
            onSubmit: $.proxy(this._onSubmit, this)
        }
    },
    _createSettings: function () {
        this.settings = {
            addDomainUrl: this.element.attr('data-addDomain-url'),
            addDomainLinkUrl: this.element.attr('data-addDomainLink-url'),
            deleteDomainUrl: this.element.attr('data-deleteDomain-url'),
            deleteDomainLinksUrl: this.element.attr('data-deleteDomainLinks-url'),
            getSettingsUrl: this.element.attr('data-getSettings-url'),
            getDomainLinksUrl: this.element.attr('data-getDomainLinks-url'),
            getDomainUrl: this.element.attr('data-getDomain-url'),
            getSelectSettingsOptions: this.element.attr('data-getSelectSettingsOptions-url'),
            updateSettingsUrl: this.element.attr('data-updateSettings-url'),
            updateDomainUrl: this.element.attr('data-updateDomain-url')
        }
    },
    _initializeImageForm: function () {
        $(".ImageUpload").ajaxForm({
            dataType: 'json',
            beforeSubmit: $.proxy(this._onBeforeSubmitImages, this),
            success: $.proxy(this._onSubmitImagesCompleted, this),
            uploadProgress: $.proxy(this._onProgress, this)
        });
    },
    _onBeforeSubmitImages: function (arr, $form, options) {
        $('#UploadWindow').dialog({ title: "Image Upload", modal: true, width: 250 });
        $('#Progressbar').progressbar();
    },
    _onDelete: function (data, event) {
        event.preventDefault();
        var menuItem = $(event.currentTarget).closest('.menuItem');
        var confirmationText = "Are you sure you wish to delete " + menuItem.find('.title').text().trim() + "? This action cannot be undone.";
        var domainID = menuItem.attr('data-itemID');

        if (confirm(confirmationText)) {
            if (domainID == this.domainID)
                this.reload = true;

            $.post(this.settings.deleteDomainUrl, { domainID: domainID }, $.proxy(this._onDeleteCompleted, this));
        }
    },
    _onDeleteCompleted: function (data) {
        if (data) {
            if (data.success) {
                alert("Domain deleted successfully.");
                LeftMenuManager.loadMenu(this.viewModel);
                if (this.reload)
                    this._onNewDomain();
                this.reload = false;
            }
            else if (data.warning) {
                if (confirm(data.error + " Are you sure you wish to delete this domain? This action cannot be undone.")) {
                    $.post(this.settings.deleteDomainUrl, { domainID: data.domainID, forced: true }, $.proxy(this._onDeleteCompleted, this));
                }
            }
        }
    },
    _onDeleteDomainLinks: function (data, event) {
        event.preventDefault();
        var domainLinksToDelete = [];
        this.element.find('input:checked').each(function (i) {
            domainLinksToDelete.push($(this).val());
        });

        if (confirm("Are you sure you wish to delete selected domain links? This action cannot be undone.")) {
            $.ajax(this.settings.deleteDomainLinksUrl, {
                type: "POST",
                data: { domainLinksIDs: domainLinksToDelete },
                traditional: true,
                success: $.proxy(this._onDeleteDomainLinksCompleted, this)
            });
        }
    },
    _onDeleteDomainLinksCompleted: function (data) {
        if (data) {
            alert("Domain links successfully deleted.");
            this._updatePage(data);
        }
    },
    _onEdit: function (data, event) {
        this._setContent(true, false, false);
        event.preventDefault();
        this.viewModel.isNewDomain(false);
        var menuItem = $(event.currentTarget).closest('.menuItem');
        this.domainID = menuItem.attr('data-itemID');

        $.post(this.settings.getDomainUrl, { domainID: this.domainID }, $.proxy(this._onEditCompleted, this));
    },
    _onEditCompleted: function (data) {
        if (data) {
            this.viewModel.sectionHeader("Edit Domain");
            this._updatePage(data);
            this._getSelectSettings();
        }
    },
    _onEditSettings: function () {
        this._setContent(false, false, true);
        $.post(this.settings.getSettingsUrl, $.proxy(this._onEditSettingsCompleted, this));
    },
    _onEditSettingsCompleted: function (data) {
        if (data) {
            this._updatePage(data);
        }
    },
    _getSelectSettings: function () {
        var context = this;
        $(".dynamic select").each(function () {
            var selectID = $(this).attr("data-selectID");
            $.post(context.settings.getSelectSettingsOptions, { settingID: selectID }, $.proxy(context._onSelectOptionsCompleted, this));
        });
    },
    _onSelectOptionsCompleted: function (data) {
        if (data && data.success) {
            var context = this;
            var selected = $(this).attr("data-savedValue");
            $.each(data.options, function (key, value) {
                var option = $("<option></option>").attr("value", value.Value).text(value.Text);
                if (selected == value.Value) {
                    option.attr('selected', 'selected');
                }
                $(context).append(option);
            });
        }
    },
    _onManage: function (data, event) {
        this._setContent(false, true, false);
        event.preventDefault();
        var menuItem = $(event.currentTarget).closest('.menuItem');
        this.domainID = menuItem.attr('data-itemID');

        $.post(this.settings.getDomainLinksUrl, { domainID: this.domainID }, $.proxy(this._onManageCompleted, this));
    },
    _onManageCompleted: function (data) {
        if (data) {
            this._updatePage(data);
        }
    },
    _onNewDomain: function () {
        this._setContent(true, false, false);
        this.viewModel.isNewDomain(true);
        this.domainID = 0;
        $.post(this.settings.getDomainUrl, $.proxy(this._onNewDomainCompleted, this));
    },
    _onNewDomainCompleted: function (data) {
        if (data) {
            this.viewModel.sectionHeader("Add Domain");
            this._updatePage(data);
            this._getSelectSettings();
        }
    },
    _onProgress: function (event, position, total, percentComplete) {
        $("#Progressbar").progressbar("value", percentComplete);
    },
    _onSubmit: function (form) {
        form = $(form);
        $.validator.unobtrusive.parse(form);
        form.validate();
        if (form.valid()) {
            var data = form.serializeArray();
            var url = '';
            if (this.isDomain)
                url = this.viewModel.isNewDomain() ? this.settings.addDomainUrl : this.settings.updateDomainUrl;
            else if (this.isDomainLinks)
                url = this.settings.addDomainLinkUrl;
            else if (this.isSettings)
                url = this.settings.updateSettingsUrl;

            $.post(url, data, $.proxy(this._onSubmitCompleted, this));
        }
        return false;
    },
    _onSubmitCompleted: function (data) {
        if (data) {
            if (this.isDomain) {
                if (data.success) {
                    alert("Domain successfully saved.");
                    LeftMenuManager.loadMenu(this.viewModel);
                    $.post(this.settings.getDomainUrl, { domainID: data.domainID }, $.proxy(this._onEditCompleted, this));
                }
            }
            else if (this.isDomainLinks) {
                alert("Domain link successfully created.");
                this._updatePage(data);
            }
            else if (this.isSettings) {
                if (data.success) {
                    alert("Settings where successfuly saved on server.");
                }
            }
        }
    },
    _onSubmitImagesCompleted: function (data) {
        if (data) {
            if (data.success) {
                $("#" + data.id).attr("src", data.src);
            }
        }
        $('#UploadWindow').dialog("close");
        $("#Progressbar").progressbar("destroy");
        $('#UploadWindow').dialog("destroy");
    },
    _setContent: function (domain, domainLinks, settings) {
        this.isDomain = domain;
        this.isDomainLinks = domainLinks;
        this.isSettings = settings;
    },
    _updatePage: function (data) {
        this.element.find('.mainContainer').html(data);
        this._applyViewModel(this.element.find('.mainContainer'));
        MessageManager.dispatchMessage(UIMessage.DocumentChanged, this);
        this._initializeImageForm();
    },
    initialize: function () {
        this._createSettings();
        this._createViewModel();
        this._applyViewModel();

        ko.bindingHandlers.fadeVisible = {
            init: function (element, valueAccessor) {
                var value = valueAccessor();
                $(element).toggle(ko.utils.unwrapObservable(value));
            },
            update: function (element, valueAccessor) {
                var value = valueAccessor();
                ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
            }
        };
    }
}

$(function () {
    var DomainsManager = new HostPipe.UI.DomainsManager();
    DomainsManager.initialize();
})